﻿using Blazui.Component;
using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using Microsoft.JSInterop;
using Project13776616780_01.Model;
using Project13776616780_01.ViewModel;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project13776616780_01.Pages
{
    enum 天干
    {
        甲 = 1,
        乙,
        丙,
        丁,
        戊,
        己,
        庚,
        辛,
        壬,
        癸
    }

    enum 地支
    {
        子 = 1,
        丑,
        寅,
        卯,
        辰,
        巳,
        午,
        未,
        申,
        酉,
        戌,
        亥
    }
    public partial class UpdateProduct
    {
        [Inject]
        private DocsDbContext dbContext { get; set; }
        private BInput<string> editor;
        private BForm form;

        [Parameter]
        public UpdateProductModel Product { get; set; }
        protected override void OnAfterRender(bool firstRender)
        {
            base.OnAfterRender(firstRender);
            if (firstRender)
            {
                _ = JSRuntime.InvokeVoidAsync("registerHtmlEditor", editor.InputElement);
            }
        }
        /// <summary>
        /// 汉字转首字母
        /// </summary>
        /// <param name="strChinese"></param>
        /// <returns></returns>
        public static string GetFirstSpell(string strChinese)
        {
            try
            {
                if (strChinese.Length != 0)
                {
                    StringBuilder fullSpell = new StringBuilder();
                    for (int i = 0; i < strChinese.Length; i++)
                    {
                        var chr = strChinese[i];
                        fullSpell.Append(GetSpell(chr)[0]);
                    }

                    return fullSpell.ToString().ToUpper();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("首字母转化出错！" + e.Message);
            }

            return string.Empty;
        }

        private static string GetSpell(char chr)
        {
            var coverchr = NPinyin.Pinyin.GetPinyin(chr);
            return coverchr[0].ToString();

        }
        private async Task SaveDataAsync()
        {
            var description = await JSRuntime.InvokeAsync<string>("SyncEditor");
            if (string.IsNullOrWhiteSpace(description))
            {
                Toast("描述不能为空");
                return;
            }
            if (!form.IsValid())
            {
                return;
            }
            var product = form.GetValue<UpdateProductModel>();
            if (Product == null)
            {
                var time = product.CreationTime.HasValue ? product.CreationTime.Value : DateTime.Now;
                ChineseLunisolarCalendar cncal = new ChineseLunisolarCalendar();
                // 获取干支纪年值
                int a = cncal.GetSexagenaryYear(time);
                // 获取天干、地支
                天干 tg = (天干)cncal.GetCelestialStem(a);
                地支 dz = (地支)cncal.GetTerrestrialBranch(a);

                string msg = $"{tg}{dz}";

                dbContext.Set<Product>().Add(new Product()
                {
                    AuthorId = product.Author.Key,
                    CategoryId = product.Category.Key,
                    CreationTime = time,
                    Description = description,
                    DescriptionTitle = product.DescriptionTitle,
                    IdNumber = GetFirstSpell(msg) + DateTime.Now.ToString("yyyyMM") + new Random().Next(100000, 999999).ToString(),
                    Image = product.Image.FirstOrDefault()?.Url,
                    Name = product.Name,
                    SizeId = product.Size.Key,
                    CompanyId = product.Company.Key
                });
            }
            else
            {
                var existProduct = await dbContext.Set<Product>().FirstOrDefaultAsync(x => x.Id == Product.Id);
                if (existProduct == null)
                {
                    Toast("藏品不存在");
                    return;
                }
                existProduct.CompanyId = product.Company.Key;
                existProduct.AuthorId = product.Author.Key;
                existProduct.CategoryId = product.Category.Key;
                existProduct.Description = description;
                existProduct.DescriptionTitle = product.DescriptionTitle;
                existProduct.Image = product.Image.FirstOrDefault().Url;
                existProduct.Name = product.Name;
                existProduct.SizeId = product.Size.Key;
            }
            await dbContext.SaveChangesAsync();
            Toast("保存成功");
            _ = CloseAsync(true);
        }
    }
}
